<template>
  <!-- 规则类型选择组件 -->
  <div class="rule_group_wrap">
    <div class="group_btns">
      <span class="rule_tit">
        组{{contentGroup+1}}
      </span>
      <span
        class="rule_add"
        @click="addRuleItem">
        <i class="el-icon-circle-plus icon"></i> 添加规则
      </span>
      <span
        class="rule_rbtn rule_del"
        @click="delRuleGroup">
        <i class="el-icon-delete icon"></i> 删除规则组
      </span>
      <span
        class="rule_rbtn rule_copy"
        @click="copyRuleGroup">
        <i class="el-icon-copy-document icon"></i> 复制规则组
      </span>
    </div>
    <div
      :class="['rItem_box',disabled ? 'disabled':'']"
      v-for="(item, index) in ruleData"
      :key="index"
    >
      <i :class="'rs_icon rs_icon'+item.modelType"></i>
      <el-select
        class="m-b-1-width m-b-1-margin"
        size="small"
        v-model="item.ruleConditionId"
        placeholder="规则字典的字段"
        clearable
        filterable
        :disabled="disabled"
        @change="changeCondition(item, index)">
        <el-option-group
          v-for="group in rcgOptionsFilter"
          :key="group.label"
          :label="group.label">
          <el-option
            v-for="_item in group.options"
            :key="_item.id"
            :label="_item.dicName"
            :value="_item.id">
            <span style="float: left">{{_item.dicName}}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{group.label.replace('预约', '')}}</span>
          </el-option>
        </el-option-group>
        <!-- <el-option
          v-for="_item in rcOptions"
          :key="_item.id"
          :label="_item.dicName"
          :value="_item.id"
        >
          <span style="float: left">{{_item.dicName+','+_item.controllType}}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{_item.modelType | flrModelTypeText}}</span>
        </el-option> -->
      </el-select>
      <el-select
        class="m-b-1-width-small m-b-1-margin"
        size="small"
        @change="conditionCodeChange(item,index)"
        v-model="item.conditionCode"
        placeholder="规则符号"
        :disabled="disabled"
      >
        <el-option
          v-for="(_item,_index) in item.signFilterOptions"
          :key="_index"
          :label="_item.label"
          :value="_item.value"
        ></el-option>
      </el-select>
      <el-input
        class="m-b-1-width-big"
        size="small"
        :disabled="disabled"
        v-model.number="item.conditionValue"
        v-if="['1','7','8','10','11','12','14','15'].includes(item.controllType)">
        <span v-if="['7','8','10','11','12','14','15'].includes(item.controllType)" slot="suffix">{{item.controllType | flrDateTypeText}}</span>
      </el-input>
      <el-input
        v-else-if="['2','13'].includes(item.controllType)"
        class="m-b-1-width-big"
        size="small"
        :disabled="disabled"
        v-model="item.conditionValue"
        :placeholder="`请输入${placeholderKey[index] ||' '}`"
        clearable></el-input>
      <el-select
        v-else-if="item.controllType==='3'"
        class="m-b-1-width-big "
        size="small"
        v-model="item.conditionValue"
        :filterable="!disabled"
        :class="disabled ? 'disabled-select-input':''"
        :allow-create="[1,2,7,8].includes(item.conditionCode)&&!disabled"
        :placeholder="`请选择${placeholderKey[index]||' '}`"
        clearable>
        <template v-if="item.conditionSelectValueOptions && item.conditionSelectValueOptions.length && typeof item.conditionSelectValueOptions[0] === 'object'">
          <el-option
            v-for="(_item,_index) in item.conditionSelectValueOptions"
            :key="_index"
            :label="_item.label"
            :value="_item.value"
            :disabled="disabled"
          ></el-option>
        </template>
        <template v-else>
          <el-option
            v-for="(_item,_index) in item.conditionSelectValueOptions"
            :key="_index"
            :label="_item"
            :value="_item"
            :disabled="disabled"
          ></el-option>
        </template>
      </el-select>
      <el-select
        v-else-if="item.controllType==='5'"
        class="m-b-1-width-big "
        size="small"
        :multiple="item.multiple"
        filterable
        :class="disabled ? 'disabled-select-input':''"
        :allow-create="[1,2,7,8].includes(item.conditionCode)"
        v-model="item.conditionValue"
        :placeholder="`请选择${placeholderKey[index]||' '}`"
        clearable
      >
        <template v-if="item.conditionSelectValueOptions && item.conditionSelectValueOptions.length && typeof item.conditionSelectValueOptions[0] === 'object'">
          <el-option
            v-for="(_item,_index) in item.conditionSelectValueOptions"
            :key="_index"
            :label="_item.label"
            :value="_item.value"
            :disabled="disabled"
          ></el-option>
        </template>
        <template v-else>
          <el-option
            v-for="(_item,_index) in item.conditionSelectValueOptions"
            :key="_index"
            :label="_item"
            :value="_item"
            :disabled="disabled"
          ></el-option>
        </template>
      </el-select>
      <el-date-picker
        v-else-if="item.controllType==='4'"
        class="m-b-1-width-big "
        size="small"
        :disabled="disabled"
        v-model="item.conditionValue"
        value-format="yyyy-MM-dd 00:00:00"
        type="date"
        placeholder="选择日期时间">
      </el-date-picker>
      <!-- <el-time-picker
        class="m-b-1-width-big"
        size="small"
        :disabled="disabled"
        v-if="item.controllType==='6'"
        v-model="item.conditionValue"
        value-format="HH:mm:ss"
        placeholder="选择时间">
      </el-time-picker> -->
      <TimePicker
        v-else-if="item.controllType==='6'"
        :time-val="item.conditionValue"
        :input-width="'62'"
        @input="val => ruleData[index].conditionValue = val"/>

      <TimeSelectPicker
        v-else-if="item.controllType==='9'"
        :time-val="item.conditionValue"
        @input="val => ruleData[index].conditionValue = val"
      />
      <!-- v-if="ruleData.length>1" -->
      <i
        :class="['el-icon-error','rc_del_icon']"
        @click="del(item, index)"
      ></i>
    </div>
  </div>
</template>

<script>
import { Options } from '@/utils/constant'
import getDicOptions from '@/mixin/getDicOptions'
import TimePicker from '@/components/timePicker/index'
import TimeSelectPicker from '@/components/timeSelectPicker/index'
import { sysAppId } from '@/settings.js'
const options = Options
const ruleItemObj = {
  ruleCondition: '',
  conditionCode: null,
  conditionCodeOld: null,
  conditionValue: '',
  ruleConditionId: '',
  controllType: '',
  modelType: null,
  ruleContentGroup: null,
  signFilterOptions: [],
  conditionSelectValueOptions: []
}
export default {
  mixins: [getDicOptions],
  components: { TimePicker, TimeSelectPicker },
  props: {
    hospitalCode: {
      // 医院代码
      type: String,
      default: ''
    },
    dep: {
      // 科室
      type: String,
      default: ''
    },
    ruleType: {
      type: Number,
      default: 2
    },
    ruleList: {
      type: Array,
      default: () => {
        return []
      }
    },
    rcgOptionsFilter: {
      type: Array,
      default: () => {
        return []
      }
    },
    rcgOptions: {
      type: Array,
      default: () => {
        return []
      }
    },
    rcOptions: {
      type: Array,
      default: () => {
        return []
      }
    },
    initMultiple: {
      type: Boolean,
      default: false
    },
    contentGroup: {
      type: Number,
      default: null
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      conditionSelectValueOptions: [], // 值的选项数据
      placeholderKey: [],
      modelType: '',
      ruleData: []
    }
  },
  watch: {
    ruleList: {
      handler(val, oldVal) {
        this.ruleData.forEach((item, index) => {
          this.conditionCodeChange(item, index)
        })
        this.$nextTick(() => {
          this.initRuleData()
        })
      },
      deep: true
    }
  },
  filters: {
    flrModelTypeText(val) {
      let txt = ''
      const _obj = Options.modelTypeOptions.find(item => item.value === val)
      if (_obj) {
        txt = _obj.label
      }
      return txt
    },
    flrDateTypeText(val) {
      let txt = ''
      switch (val) {
        case '7':
        case '15':
          txt = '分钟'
          break
        case '14':
          txt = '小时'
          break
        case '8':
        case '10':
          txt = '天'
          break
        case '11':
          txt = '周'
          break
        case '12':
          txt = '月'
          break
      }
      return txt
    }
  },
  mounted() {
    this.$nextTick(() => {
      // 初始化
      this.initRuleData()
    })
  },
  methods: {
    // 添加场景条件
    addRuleItem(type) {
      let rObj = JSON.parse(JSON.stringify(ruleItemObj))
      rObj.modelType = type || null
      rObj.ruleContentGroup = this.contentGroup
      this.ruleData.push(rObj)
    },
    delRuleGroup() {
      this.$emit('delGroup', this.contentGroup)
    },
    copyRuleGroup() {
      this.$emit('copyGroup', this.contentGroup)
    },
    // 初始化
    initRuleData() {
      const rd = JSON.parse(JSON.stringify(this.ruleList))
      rd.sort(function (a, b) { return b.modelType - a.modelType })
      rd.forEach(v => {
        v.conditionCodeOld = v.conditionCode
        // v.ruleContentGroup = this.contentGroup
      })
      // 若是配置了规则组，则过滤掉modelType=1的数据
      let ruleData = []
      rd.forEach(item => {
        console.log('modelType', item.modelType)
        if (this.ruleType == 2 && item.modelType == 1) {
          ruleData.push(item)
        }
        if (this.ruleType == 9 && item.modelType == 3) {
          ruleData.push(item)
        }
      })
      this.ruleData = ruleData
      console.log('ruleData==>', ruleData)
      if (this.ruleData.length === 0) {
        this.addRuleItem()
        if (this.initMultiple) {
          this.addRuleItem()
        }
      } else {
        for (let i = 0; i < this.ruleData.length; i++) {
          this.getControlAndValue(this.ruleData[i], i)
          this.getSignFilterOptions(this.ruleData[i], i)
        }
      }
    },
    // 检查规则判断是否重复，以及号源比例类型只能选择一个类型判断
    calSelectedToo(obj, index) {
      const excludesType = ['9', '11', '13']
      if (!excludesType.includes(obj.controllType)) {
        if (obj.modelType === 4) {
          const _o = this.ruleData.find(item => item.modelType === obj.modelType)
          console.log('_o_=====>2', _o)
          if (_o) {
            this.$message.warning('号源比例类型，选项不能多选！')
            this.ruleData[index].ruleConditionId = ''
            return false
          }
        }
        // else if (this.ruleData[index].modelType) {
        //   const _o = this.ruleData.filter(item => item.ruleConditionId === obj.id)
        //   if (_o.length > 1) {
        //     this.$message.warning(`${obj.dicName}，已存在！`)
        //     this.ruleData[index] = JSON.parse(JSON.stringify(ruleItemObj))
        //     this.ruleData = JSON.parse(JSON.stringify(this.ruleData))
        //     return false
        //   }
        // }
      } else {
        // const _o = this.ruleData.filter(item => item.ruleConditionId === obj.id)
        // if (_o.length > 1) {
        //   this.$message.warning(`${obj.dicName}，已存在！`)
        //   this.ruleData[index].ruleConditionId = ''
        //   return false
        // }
      }
      return true
    },
    changeCondition(row, index) {
      this.ruleData[index].conditionValue = ''
      this.ruleData[index].conditionCode = null
      let obj = this.rcOptions.find(v => {
        return v.id === row.ruleConditionId
      })
      if (obj && this.calSelectedToo(obj, index)) {
        this.ruleData[index].ruleCondition = obj ? obj.dicEname : ''
        this.ruleData[index].controllType = obj ? obj.controllType : ''
        this.$nextTick(() => {
          this.getControlAndValue(row, index)
          this.getSignFilterOptions(row, index)
        })
      }
    },
    async getControlAndValue(_item, _index) {
      // 找remark 判断控件
      // index 是 _item在规则数据字典中的位置
      let index = this.rcOptions.findIndex(item => item.id === _item.ruleConditionId)
      // 规则数据字典存在
      if (index !== -1) {
        this.placeholderKey[_index] = this.rcOptions[index].dicName
        // 存在conditionValue、是字符串、多选择的控件array，需要进行convert '1,2'=>[1,2]
        if (this.rcOptions[index].controllType === '5' &&
          (_item.conditionCode === 9 || _item.conditionCode === 10) &&
          _item.conditionValue &&
          typeof _item.conditionValue === 'string'
        ) {
          this.ruleData[_index].conditionValue = this.ruleData[_index].conditionValue.split(',')
          this.ruleData[_index].multiple = true
        }
        // 获取相应控件
        this.ruleData[_index].controllType = this.rcOptions[index].controllType
        this.ruleData[_index].modelType = this.rcOptions[index].modelType
        // 获取相应的方法 来获取控件里面的数值
        if (this.rcOptions[index].clientMethod) {
          // 获取下列方法名字 例如 mx_getDicMethod(getDepArea, params ) 引用混入方法
          const params = {
            HospitalCode: this.hospitalCode,
            Dep: this.dep,
            type: '班次',
            SysAppId: sysAppId // 新增
          }
          this.ruleData[_index].conditionSelectValueOptions = []// 先清空
          const resDicOptions = await this.mx_getDicMethod(this.rcOptions[index].clientMethod, params)
          this.ruleData[_index].conditionSelectValueOptions = resDicOptions
          this.$forceUpdate()
        } else {
          console.log('不存在相应方法')
        }
      }
    },
    conditionCodeChange(_item, _index) {
      console.log('待查看规则符号改变conditionCodeChange', _item) // 这里ruleContentGroup正常
      if (([1, 2, 3, 4, 5, 6].includes(_item.conditionCode) && [1, 2, 3, 4, 5, 6].includes(_item.conditionCodeOld)) ||
        ([7, 8].includes(_item.conditionCode) && [7, 8].includes(_item.conditionCodeOld)) ||
        ([9, 10].includes(_item.conditionCode) && [9, 10].includes(_item.conditionCodeOld))) {
        // 不用清空数据
      } else {
      // 需要清空数据
        console.log('_item.conditionCode', _item.conditionCode)
        if (_item.conditionCode === 9 || _item.conditionCode === 10) {
          this.ruleData[_index].conditionValue = ''
          this.$nextTick(() => {
            this.ruleData[_index].multiple = true
            this.ruleData[_index].conditionValue = []
            this.ruleData[_index].ruleContentGroup = _item.ruleContentGroup
            console.log('this.ruleData', this.ruleData)
            console.log('this.ruleData[_index].ruleContentGroup', this.ruleData[_index].ruleContentGroup)
          })
        } else {
          this.ruleData[_index].conditionValue = ''
          this.$nextTick(() => {
            this.ruleData[_index].multiple = false
            this.$forceUpdate()
          })
        }
      }
      _item.conditionCodeOld = _item.conditionCode
      this.$forceUpdate()
    },
    // 获取符号选项
    getSignFilterOptions(row, index) {
      // { value: 1, label: '等于' },
      // { value: 2, label: '不等于' },
      // { value: 3, label: '大于' },
      // { value: 4, label: '大于等于' },
      // { value: 5, label: '小于' },
      // { value: 6, label: '小于等于' },
      // { value: 7, label: '包含' },
      // { value: 8, label: '不包含' },
      // { value: 9, label: '在列表' },
      // { value: 10, label: '不在列表' }
      let sOption = []
      // const cType = row ? row.controllType : ''
      const rc = this.rcOptions.find(item => item.id === row.ruleConditionId)
      const cType = rc ? rc.controllType : ''
      if (['1', '4', '6', '7', '8', '10', '11', '12', '14', '15'].includes(cType)) {
        if (row.modelType === 4) {
          // 号源比例，规则类型的选项过滤就使用一种等于
          sOption = options.signOptions.filter(item => [1].indexOf(item.value) >= 0)
        } else {
          sOption = options.signOptions.filter(item => [1, 2, 3, 4, 5, 6].indexOf(item.value) >= 0)
        }
      } else if (cType === '2' || cType === '3') {
        sOption = options.signOptions.filter(item => [1, 2, 7, 8].indexOf(item.value) >= 0)
      } else if (cType === '5') {
        sOption = options.signOptions.filter(item => [1, 2, 7, 8, 9, 10].indexOf(item.value) >= 0)
      } else if (cType === '9' || cType === '13') {
        sOption = options.signOptions.filter(item => [1].indexOf(item.value) >= 0)
      }
      this.ruleData[index].signFilterOptions = JSON.parse(JSON.stringify(sOption))
      // 如果符号选项有值，默认选择第一个。如果已选择，使用已选择
      if (sOption.length > 0) {
        this.ruleData[index].conditionCode = this.ruleData[index].conditionCode || sOption[0].value
        console.log('this.ruleData[index].conditionCode', this.ruleData[index].conditionCode)
      }
      console.log('待查看this.ruleData_getSignFilterOptions', this.ruleData)
    },
    // 符号改变
    codeChange() {
      console.log(this.rCode)
    },
    getRuleData() {
      return JSON.parse(JSON.stringify(this.ruleData))
    },
    // 删除
    del(row, index) {
      this.ruleData.splice(index, 1)
      this.$emit('del')
    }
  }
}
</script>

<style lang="scss" scoped>
.el-input{
  width:auto;
}
.rItem_box{
  position: relative;
  padding-right: 18px;
  padding-left: 3px;
  line-height: 34px;
  .m-b-1-width{
    /deep/ .el-input__inner{
      width:160px;
    }
  }
  .m-b-1-width-small{
    /deep/ .el-input__inner{
      width:100px;
    }
  }
  .m-b-1-width-big{
    /deep/ .el-input__inner{
      width:210px;
    }
  }
  .m-b-1-margin{
    margin-right: 4px;
  }

  &:hover:not(.disabled){
    background-color: rgba(0, 191, 239, 0.1);
    .rc_del_icon{
      display: inline-block;
    }
  }
  .rc_del_icon{
    position: absolute;
    right: 2px;
    top: 50%;
    z-index: 2;
    cursor: pointer;
    display:none;
    transform: translateY(-50%);
  }
  /deep/ .el-input.is-disabled .el-input__inner{
    cursor: auto;
    background-color: #FFF;
    border-color:#DCDFE6;
    color: #606266;
  }
  /deep/ .el-input.is-disabled .el-input__icon{
      cursor: auto;
  }
  /deep/ .disabled-select-input{
      .el-tag__close{
          display:none
      }
      .el-icon-circle-close{
          display:none
      }
      .el-select__input{
          display: none;
      }
  }
}
.rule_tit{
  font-size: 12px;
  color: #333;
  font-weight: bold;
  margin: 0 10px;
}
.rule_add{
  font-size: 12px;
  // margin-left: 10px;
  cursor: pointer;
  color: #00C0EF;
}
.rule_rbtn{
  float: right;
  margin-right: 10px;
  font-size: 12px;
  cursor: pointer;
  color: #00C0EF;
}
.rule_del{
  color: #ff5c5c;
}
.rule_copy{
  color: #00C0EF;
}
.group_btns{
  line-height: 30px;
}
</style>
<style>
.disabled-select-pop{
    pointer-events: none;
}
</style>
